<template>
  <div class="AddCollectMoney">
    <div>
      <h4 v-if="$route.params.state === 'Edit'">编辑收费模板</h4>
      <h4 v-else>新增收费模板</h4>
    </div>
    <div class="key-search">
      <el-form ref="validate" :model="BindForm" :rules="pattern">
        <el-form-item
          label="模板名称"
          prop="templateName"
          class="ele-from-item"
        >
          <el-col :span="20">
            <el-input
              v-model="BindForm.templateName"
              class="cus-input"
              placeholder="模板名称"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="备注" class="ele-from-item">
          <el-col :span="20">
            <el-input
              v-model="BindForm.remarks"
              class="cus-input"
              maxlength="20"
              placeholder="备注"
            />
          </el-col>
        </el-form-item>
        <!-- <div class="cus-title-1">
          <b>租赁设置</b>
        </div>
        <el-form-item label="押金" prop="deposit" class="yj-form-item">
          <el-col :span="22">
            <div>
              <el-input v-model="BindForm.deposit" placeholder="输入押金金额" />
              <span>元</span>
              <span
                style="margin-left:100px;color:gray"
              >填写0为不需要缴纳押金</span>
            </div>
          </el-col>
        </el-form-item> -->
        <div class="cus-title-2">
          <b>租赁设置</b>
          <el-button type="text" :disabled="true">查看租金计算方式</el-button>
        </div>
        <!--        <el-form-item label="基础收费" required>-->
        <!--          <div class="jcsf">-->
        <!--            <el-form-item prop="unitPrice" class="dz-form-item">-->
        <!--              <b>单价:</b>-->
        <!--              <el-input-number-->
        <!--                v-model="BindForm.unitPrice"-->
        <!--                placeholder="输入金额"-->
        <!--                :controls="false"-->
        <!--                :precision="2"-->
        <!--                :min="0.01"-->
        <!--                :max="9999"-->
        <!--              />-->
        <!--              <span>元/天</span>-->
        <!--            </el-form-item>-->
        <!--            <el-form-item prop="day" class="zd-form-item">-->
        <!--              <span>最低限制:</span>-->
        <!--              <el-input-number-->
        <!--                v-model="BindForm.day"-->
        <!--                :controls="false"-->
        <!--                :min="1"-->
        <!--                :max="9999"-->
        <!--                :precision="0"-->
        <!--                placeholder="输入金额"-->
        <!--              />-->
        <!--              <span>天起</span>-->
        <!--            </el-form-item>-->
        <!--          </div>-->

        <!--          &lt;!&ndash; <el-row :gutter="24">-->
        <!--            <el-col :span="5" />-->
        <!--            <el-col :span="16" />-->
        <!--          </el-row> &ndash;&gt;-->
        <!--        </el-form-item>-->
        <el-form-item label="封顶收费" required>
          <el-col :span="22">
            <div>
              <div style="display:flex;align-items:center">
                <el-radio
                  v-model="BindForm.cappinCharge"
                  label="0"
                  @change="BindForm.customPrice = 0"
                >按原价价格</el-radio>
                <span style="margin-left:20%;color:gray">
                  最高收费金额，达到该金额后，不再进行计费。
                </span>
              </div>
              <div style="display:flex;align-items: center;">
                <el-radio v-model="BindForm.cappinCharge" label="1">
                  自定义价格
                </el-radio>

                <el-form-item prop="customPrice">
                  <el-input-number
                    v-model="BindForm.customPrice"
                    :controls="false"
                    :precision="2"
                    :min="0.01"
                    :max="9999"
                    :disabled="BindForm.cappinCharge == '0'"
                  />
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-form-item>
        <div v-for="(item,index) in BindForm.collectModelList" :key="index" style="margin-bottom: 22px;">
          <collect-money-model v-if="index==0" ref="collectMoneyModel" :index="index" :collection-form="item" />
          <collect-money-model v-if="index>0" ref="collectMoneyModel" :index="index" :collection-form="item" :min-rent-day="BindForm.collectModelList[index-1].startRentDay" @delModel="delModel" />
        </div>
        <el-form-item>
          <el-button type="text" @click="addCollectMoney">添加收费方式</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            style="width:200px;height:50px;margin-left:40%;margin-top:100px"
            type="primary"
            :disabled="disabled"
            @click="handelSubmit()"
          >提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
/** 添加收费模板 */
import {
  collectMoneyTemplateAdd,
  collectMoneyTemplateEdit
} from '@/api/customAPI/shop/CollectMoneyTemplate'
import validate from '@/utils/formValidate'
import CollectMoneyModel from '@/components/CollectMoneyModel'
export default {
  name: 'AddCollectMoney',
  components: { CollectMoneyModel },
  data() {
    return {
      validate,
      disabled: false,
      BindForm: {
        templateName: '',
        remarks: '',
        /*    deposit: '',
        unitPrice: '',
        day: '',*/
        customPrice: 0,
        cappinCharge: '0',
        collectModelList: [{
          id: null,
          startRentDay: null,
          unitPrice: null,
          ladderCharge: [
            {
              begin: 0,
              price: 1
            }
          ]
        }]
      },
      pattern: {
        customPrice: [
          { required: true, message: '请输入自定义价格', trigger: 'blur' },
          { trigger: 'change', validator: validate.isFloateger }
        ],
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
          { message: '超过限定20字符', max: 20, trigger: 'change' }
        ],
        cappinCharge: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.loadEditInfo()
  },
  methods: {
    // 初始化需要编辑的信息
    loadEditInfo() {
      console.log('编辑信息初始化：', this.$route.params)
      if (this.$route.params) {
        if (this.$route.params.state || this.$route.params.state === 'copy') {
          this.BindForm.templateName = this.$route.params.row.name
          this.BindForm.remarks = this.$route.params.row.remark
          // this.BindForm.deposit = this.$route.params.row.deposit.toString()
          /* this.BindForm.unitPrice = this.$route.params.row.basePrice.toString()
          this.BindForm.day = this.$route.params.row.baseDay ? this.$route.params.row.baseDay.toString() : ''*/
          this.BindForm.customPrice = this.$route.params.row.topPrice ? this.$route.params.row.topPrice.toString() : ''
          this.BindForm.cappinCharge = this.$route.params.row.topPriceType.toString()
          /* this.BindForm.ladderCharge = JSON.parse(
            this.$route.params.row.ladderPrice
          )*/
          if (this.$route.params.row.collectModelList) {
            console.log(this.$route.params.row.collectModelList)
            const list = this.$route.params.row.collectModelList
            this.BindForm.collectModelList = []
            list.forEach(item => {
              this.BindForm.collectModelList.push({
                id: item.id,
                startRentDay: item.baseDay,
                unitPrice: item.basePrice,
                ladderCharge: JSON.parse(item.ladderPrice)
              })
            })
          }
        }
      }
    },
    /** 添加收费模板*/
    addCollectMoney() {
      if (this.BindForm.collectModelList.length < 5) {
        this.BindForm.collectModelList.push({
          id: null,
          startRentDay: null,
          unitPrice: null,
          ladderCharge: [
            {
              begin: 0,
              price: 1
            }
          ]
        })
        this.$nextTick(() => {
          this.$refs.collectMoneyModel.forEach((item, index) => {
            if (index == this.BindForm.collectModelList.length - 2) {
              item.setDisabled(true)
            }
          })
        })
      } else {
        this.$message.error('收费方式不能超过5个')
      }
    },
    /** 删除收费模板*/
    delModel(index) {
      this.BindForm.collectModelList.splice(index, 1)
      this.$nextTick(() => {
        this.$refs.collectMoneyModel.forEach((item, index) => {
          if (index == this.BindForm.collectModelList.length - 1) {
            item.setDisabled(false)
          }
        })
      })
    },
    handelSubmit() {
      this.disabled = true
      this.$refs.validate.validate(v => {
        if (v) {
          this.$nextTick(() => {
            let allValidate = true
            this.$refs.collectMoneyModel.forEach(item => {
              console.log(item.validate())
              if (!item.validate()) {
                allValidate = false
              }
            })
            if (allValidate) {
              if (this.$route.params.state === 'Edit') {
                console.log(this.BindForm)
                const data = this.$XEUtils.clone(this.BindForm, true)
                for (let i = 0; i < data.collectModelList.length; i++) {
                  if (!data.collectModelList[i].startRentDay || !data.collectModelList[i].unitPrice) {
                    return
                  }
                  for (let j = 0; j < data.collectModelList[i].ladderCharge.length; j++) {
                    if (!data.collectModelList[i].ladderCharge[j].begin || !data.collectModelList[i].ladderCharge[j].price) {
                      return
                    }
                  }
                }
                data['templateId'] = this.$route.params.row.id
                collectMoneyTemplateEdit(data)
                  .then(result => {
                    this.$message.success('成功')
                    this.disabled = false
                    this.$store.dispatch('tagsView/delView', this.$route)
                    this.$router.go(-1)
                  })
                  .catch(() => {
                    // this.$message.error('失败：' + err)
                    this.disabled = false
                  })
              } else {
                console.log(this.BindForm)
                const data = this.$XEUtils.clone(this.BindForm, true)
                for (let i = 0; i < data.collectModelList.length; i++) {
                  if (!data.collectModelList[i].startRentDay || !data.collectModelList[i].unitPrice) {
                    return
                  }
                  for (let j = 0; j < data.collectModelList[i].ladderCharge.length; j++) {
                    if (!data.collectModelList[i].ladderCharge[j].begin || !data.collectModelList[i].ladderCharge[j].price) {
                      return
                    }
                  }
                }
                data['shopId'] = localStorage.getItem('shopId')
                collectMoneyTemplateAdd(data)
                  .then(inf => {
                    this.$message.success('成功')
                    this.disabled = false
                    this.$store.dispatch('tagsView/delView', this.$route)
                    this.$router.go(-1)
                  })
                  .catch(() => {
                    this.disabled = false
                    // this.$message.error('失败：' + err)
                  })
              }
            } else {
              this.disabled = false
            }
          })
        } else {
          // this.$message.warning('有未填项！')
          this.disabled = false
        }
      })
    },
    /* leasevali(rules, value, collback) {
      if (this.BindForm.day) {
        if (/^\d*\d\d*$/.test(value)) {
          if (rules.index === 0) {
            if (this.BindForm.day < value) {
              collback()
            } else {
              collback(new Error('天数必须大于最低限制天数'))
            }
          } else {
            if (
              this.BindForm.ladderCharge[rules.index].begin >
              this.BindForm.ladderCharge[rules.index - 1].begin
            ) {
              collback()
            } else {
              collback(new Error(`当前租赁小于阶梯${rules.index}的租赁额`))
            }
          }
        } else {
          collback()
        }
      } else {
        collback()
      }
    },*/
    /* pricevali(rules, value, collback) {
      if (value) {
        if (rules.index === 0) {
          if (this.BindForm.unitPrice > value) {
            collback()
          } else {
            collback(new Error('金额必须小于单价的金额'))
          }
        } else {
          if (
            this.BindForm.ladderCharge[rules.index].price <
            this.BindForm.ladderCharge[rules.index - 1].price
          ) {
            collback()
          } else {
            console.log(
              this.BindForm.ladderCharge[rules.index].price,
              this.BindForm.ladderCharge[rules.index - 1].price
            )
            collback(new Error(`当前单价大于阶梯${rules.index}的单价`))
          }
        }
      } else {
        collback()
      }
    },*/
    days(rules, value, collback) {
      if (value) {
        if (/^\d*\d\d*$/.test(value)) {
          collback()
        } else {
          collback(new Error('请输入正整数'))
        }
      } else {
        collback()
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    // ....
    this.$store.dispatch('tagsView/delView', from)
    next()
  },
  beforeRouteEnter(to, from, next) {
    if (to.params.state === 'Edit') {
      to.meta.title = '编辑收费模板'
    } else {
      to.meta.title = '添加收费模板'
    }
    next()
  }
}
</script>

<style lang="scss" scoped>
.AddCollectMoney {
  padding: 50px 100px;
  .key-search {
    ::v-deep.el-form {
      margin-top: 40px;
      .ele-from-item {
        .el-form-item__error {
          margin-left: 100px;
        }
      }
      .el-form-item__label {
        width: 100px;
        text-align: start;
      }
      .yj-form-item {
        .el-form-item__error {
          margin-left: 100px;
        }
      }
      .jcsf {
        display: flex;
        flex-wrap: wrap;
        .dz-form-item {
          margin-right: 60px;
          .el-form-item__error {
            margin-left: 35px;
          }
        }
      }

      .zd-form-item {
        .el-form-item__error {
          margin-left: 60px;
        }
      }
      .el-form-item {
        padding-left: 20px;
        .el-input {
          width: 200px;
        }
      }
      .cus-title-1,
      .cus-title-2 {
        width: 100%;
        height: 50px;
        line-height: 50px;
        border-radius: 5px;
        background: #f3f3f3;
        padding: 0px 20px;
        margin-bottom: 40px;
      }
      .cus-title-2 {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .PSQY,
      .XZSF {
        width: 100%;
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        p {
          margin: 0;
          .el-input {
            width: 100px;
            padding: 0px 10px;
          }
        }
        p:last-child {
          margin-left: 30px;
        }
      }
      .CUS-JTSF {
        display: flex;
        .cus-a {
          font-size: 14px;
          width: 100px;
          padding-left: 29px;
          padding-top: 10px;
        }
        .cus-template {
          width: 100%;
          .cus-div-1 {
            font-size: 15px;
            display: flex;
            align-items: center;
            padding-bottom: 25px;
            b {
              width: 60px;
            }
            span {
              display: inline-block;
            }
            .el-form-item {
              margin: 0;
              padding: 0;
            }
            .cus-span-1 {
              width: 70px;
            }
            .cus-span-2 {
              width: 40px;
            }
          }
        }
      }
      .cus-btn {
        margin-left: 95px;
      }
    }
  }
}
@media screen and (max-width: 1440px) {
  .AddCollectMoney {
    .key-search {
      .jcsf {
        .zd-form-item {
          margin-top: 20px;
        }
      }
    }
  }
}
</style>
